<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/blog/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/blog/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/blog/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/blog/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/blog/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/blog/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/blog/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="synchronized,lock,">










<meta name="description" content="synchronized为什么使用synchronized在上一章中说了volatile，在多线程下可以保证变量的可见性，但是不能保证原子性，下面一段代码说明：12345678910111213141516171819202122private volatile int flag=0;   public  void increase() &amp;#123;       flag++;   &amp;#125;">
<meta name="keywords" content="synchronized,lock">
<meta property="og:type" content="article">
<meta property="og:title" content="Java并发编程四synchronized和lock">
<meta property="og:url" content="https://zgsir.gitee.io/blog/2019/05/26/Java并发编程四synchronized和lock/index.html">
<meta property="og:site_name" content="zhaoSir">
<meta property="og:description" content="synchronized为什么使用synchronized在上一章中说了volatile，在多线程下可以保证变量的可见性，但是不能保证原子性，下面一段代码说明：12345678910111213141516171819202122private volatile int flag=0;   public  void increase() &amp;#123;       flag++;   &amp;#125;">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="https://s2.ax1x.com/2019/05/26/VEldMT.png">
<meta property="og:image" content="https://s2.ax1x.com/2019/05/26/VElrdJ.png">
<meta property="og:image" content="https://s2.ax1x.com/2019/05/26/VElDZ4.png">
<meta property="og:image" content="https://s2.ax1x.com/2019/05/26/VEl0LF.png">
<meta property="og:image" content="https://s2.ax1x.com/2019/05/26/VElwsU.png">
<meta property="og:image" content="https://s2.ax1x.com/2019/05/26/VElso9.png">
<meta property="og:image" content="https://s2.ax1x.com/2019/05/26/VEl6iR.png">
<meta property="og:updated_time" content="2019-06-03T12:38:51.691Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Java并发编程四synchronized和lock">
<meta name="twitter:description" content="synchronized为什么使用synchronized在上一章中说了volatile，在多线程下可以保证变量的可见性，但是不能保证原子性，下面一段代码说明：12345678910111213141516171819202122private volatile int flag=0;   public  void increase() &amp;#123;       flag++;   &amp;#125;">
<meta name="twitter:image" content="https://s2.ax1x.com/2019/05/26/VEldMT.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/blog/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://zgsir.gitee.io/blog/2019/05/26/Java并发编程四synchronized和lock/">





  <title>Java并发编程四synchronized和lock | zhaoSir</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/blog/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">zhaoSir</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">一个不正经的后台开发攻城狮</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/blog/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/blog/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/blog/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/blog/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br>
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/blog/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://zgsir.gitee.io/blog/blog/2019/05/26/Java并发编程四synchronized和lock/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="zhaoSir">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/blog/images/head.jpeg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="zhaoSir">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">Java并发编程四synchronized和lock</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2019-05-26T13:18:43+08:00">
                2019-05-26
              </time>
            

            
              <span class="post-meta-divider">|</span>
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-check-o"></i>
              </span>
              
                <span class="post-meta-item-text">更新于&#58;</span>
              
              <time title="更新于" itemprop="dateModified" datetime="2019-06-03T20:38:51+08:00">
                2019-06-03
              </time>
            
          </span>
          
          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blog/categories/Java并发/" itemprop="url" rel="index">
                    <span itemprop="name">Java并发</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          
            <span class="post-meta-divider">|</span>
            <span class="page-pv"><i class="fa fa-eye"></i> 阅读
            <span class="busuanzi-value" id="busuanzi_value_page_pv"></span>次
            </span>
          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  3k
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  11分钟
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h1 id="synchronized"><a href="#synchronized" class="headerlink" title="synchronized"></a>synchronized</h1><h2 id="为什么使用synchronized"><a href="#为什么使用synchronized" class="headerlink" title="为什么使用synchronized"></a>为什么使用synchronized</h2><p>在上一章中说了volatile，在多线程下可以保证变量的可见性，但是不能保证原子性，下面一段代码说明：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line">private volatile int flag=0;</span><br><span class="line">   public  void increase() &#123;</span><br><span class="line">       flag++;</span><br><span class="line">   &#125;</span><br><span class="line">   public static void main(String[] args)&#123;</span><br><span class="line">       SynchronizedThread test = new SynchronizedThread();</span><br><span class="line">       // 启10个线程 </span><br><span class="line">       for (int i = 0; i &lt;10; i++) &#123;</span><br><span class="line">           new Thread(()-&gt;&#123;</span><br><span class="line">           // 每个线程对flag进来i++ 1000次</span><br><span class="line">               for (int j = 0; j &lt;1000 ; j++) &#123;</span><br><span class="line">                   test.increase();</span><br><span class="line">               &#125;</span><br><span class="line">           &#125;).start();</span><br><span class="line">       &#125;</span><br><span class="line">       //保证前面的线程都执行完</span><br><span class="line">       while(Thread.activeCount()&gt;2)&#123;</span><br><span class="line">           Thread.yield();</span><br><span class="line">       &#125;</span><br><span class="line">       // 理想值为10000</span><br><span class="line">       System.out.println(test.flag);</span><br><span class="line">   &#125;</span><br></pre></td></tr></table></figure></p>
<p>运行上面代码，会发现输出flag的值不是理想中10000，虽然volatile写入时候会通知其他线程的工作内存值无效，从主内存重写读取。i++是三步操作，读取-赋值-写入不能保证原子性。<strong>原子性：不能被中断要么成功要么失败。</strong><br><strong>比如此时主内存的flag值10，线程1和线程2读取到自己工作内存都是10，然后线程1在进行赋值的时候，线程2执行了，这时线程2发现自己内存的值和主内存的值一样，并没有修改，然后赋值写入11，此时线程1运行，因为之前读过了，会往下继续运行写入也是11。那么两个线程相当于只增加了一次</strong>。要想达到理想值，只需要修改<code>public synchronized void increase() {  flag++; }</code>就行了。</p>
<h2 id="什么是synchronized"><a href="#什么是synchronized" class="headerlink" title="什么是synchronized"></a>什么是synchronized</h2><p><strong>Java提供的一种原子性性内置锁，Java每个对象都可以把它当做是监视器锁，线程代码执行在进入synchronized代码块时候会自动获取内部锁，这个时候其他线程访问时候会被阻塞到队列，直到进入synchronized中的代码执行完毕或者抛出异常或者调用了wait方法，都会释放锁资源。在进入synchronized会从主内存把变量读取到自己工作内存，在退出的时候会把工作内存的值写入到主内存，保证了原子性。</strong></p>
<h2 id="synchronized机制"><a href="#synchronized机制" class="headerlink" title="synchronized机制"></a>synchronized机制</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">public class Test &#123;</span><br><span class="line">    public static void main(String[] args) &#123;</span><br><span class="line">        synchronized (Test.class)&#123;</span><br><span class="line"></span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>编译后执行<strong>javap -v Test.class</strong>就会发现两条指令。<br><img src="https://s2.ax1x.com/2019/05/26/VEldMT.png" alt="在这里插入图片描述"><br><strong>synchronized是使用一种monitor机制，在进入锁时候先执行monitorenter指令。退出的时候执行monitorexit指令。synchronized是可重入锁，每个对象中都含有一个计数器当前线程再次获取锁，计数器+1，退出时候计算器-1，直到计数器为0才释放锁资源，唤醒其他线程来争抢资源。任意一个对象都拥有自己的监视器，只有在线程获取到监视器锁时才会进入代码中，否则就进入阻塞状态。</strong><br><img src="https://s2.ax1x.com/2019/05/26/VElrdJ.png" alt="在这里插入图片描述"></p>
<h2 id="synchronized使用场景"><a href="#synchronized使用场景" class="headerlink" title="synchronized使用场景"></a>synchronized使用场景</h2><ol>
<li>对于普通方法，锁是当前类实例对象。</li>
<li>对于静态方法，锁是当前类对象。</li>
<li>对于同步代码块，锁是synchronized括号里的对象。</li>
</ol>
<h2 id="synchronized锁升级"><a href="#synchronized锁升级" class="headerlink" title="synchronized锁升级"></a>synchronized锁升级</h2><p><strong>synchronized在1.6以前是重量级锁，当前只有一个线程执行，其他线程阻塞。为了减少获得锁和释放锁带来的性能问题，而引入了偏向锁、轻量级锁以及锁的存储过程和升级过程。在1.6后锁分为了无锁、偏向锁、轻量锁、重量锁，锁的状态在多线程竞争的情况下会逐渐升级，只能升级而不能降级，这样是为了提高锁获取和释放的效率。</strong><br>synchronized的锁是存贮在Java对象头里的，如果对象是数组类型，则虚拟机用3个字宽（Word）存储对象头，如果对象是非数组类型，则用2字宽存储对象头。1个字宽等于4个字节。<br><img src="https://s2.ax1x.com/2019/05/26/VElDZ4.png" alt="在这里插入图片描述"><br>Java对象头中的Mark Word里默认存储了对象是HashCode、分代年龄、和锁标记。<br><img src="https://s2.ax1x.com/2019/05/26/VEl0LF.png" alt="在这里插入图片描述"><br>在运行的时候，Mark Word里存储的数据会随着锁标志位的变化而变化，可能会变化为存储以下四种形式。<br><img src="https://s2.ax1x.com/2019/05/26/VElwsU.png" alt="在这里插入图片描述"></p>
<h3 id="偏向锁"><a href="#偏向锁" class="headerlink" title="偏向锁"></a>偏向锁</h3><p>偏向锁的意思未来只有一个线程使用锁，不会有其他线程来争取。<br>获取锁：</p>
<ol>
<li>首先检查Mark word中锁的标志是否为01。</li>
<li>如果是01，判断对象头的Mark word记录是否为当前线程ID，如果是执行5，否则执行3.</li>
<li>线程ID并未只指向自己，发送CAS竞争，如果竞争成功，则将Mark Word中线程ID设置为当前线程ID，执行5；如果未成功执行4。</li>
<li>当到达全局安全点（在这个时间点上没有正在执行的字节码）时获得偏向锁的线程被挂起，偏向锁升级为轻量级锁，然后被阻塞在安全点的线程继续往下执行同步代码。</li>
<li>执行同步代码。</li>
</ol>
<p>撤销锁：偏向锁使用了一种等到竞争出现才释放锁的机制，所以当其他线程尝试竞争偏向锁时，持有偏向锁的线程才会释放锁。需要等待全局安全点，它首先暂停原持有偏向锁的线程，然后检查线程是否还在活着，如果线程处于未活动状态，则释放锁标记，如果处于活动状态则升级为轻量级锁。</p>
<h3 id="CAS"><a href="#CAS" class="headerlink" title="CAS"></a>CAS</h3><p><strong>CAS全称是Compare And Swap 即比较并交换，使用乐观锁机制，包含三个操作数 —— 内存位置（V）、预期原值（A）和新值(B)。 如果内存位置的值与预期原值相匹配，那么才会将该位置值更新为新值 。否则，处理器不做任何操作。</strong></p>
<h3 id="轻量级锁"><a href="#轻量级锁" class="headerlink" title="轻量级锁"></a>轻量级锁</h3><p>线程在执行同步代码块之前，JVM会先在当前线程的栈桢中创建用于存储锁记录的空间，并<br>将对象头中的Mark Word复制到锁记录中，官方称为Displaced Mark Word。<br>加锁：</p>
<ol>
<li>CAS修改Mark Word，如果成功指向栈中锁记录的指针执行3，如果失败执行2.</li>
<li>发生自旋，自旋到一定次数，如果修改成功执行3，否则锁膨胀为重量级锁。</li>
<li>执行同步代码块。<br>解锁：<br>轻量级解锁时，会使用原子的CAS操作将Displaced Mark Word替换回到对象头，如果成<br>功，则表示没有竞争发生。如果失败，表示当前锁存在竞争，锁就会膨胀成重量级锁。</li>
</ol>
<h3 id="锁的优缺点"><a href="#锁的优缺点" class="headerlink" title="锁的优缺点"></a>锁的优缺点</h3><table>
<thead>
<tr>
<th>锁</th>
<th>优点</th>
<th>缺点</th>
<th>使用场景</th>
</tr>
</thead>
<tbody>
<tr>
<td>偏向锁</td>
<td>加锁和解锁不需要额外的消耗</td>
<td>如果线程出现竞争，会带来额外的锁撤销的消耗</td>
<td>适用于当前只有一个线程访问同步块场景</td>
</tr>
<tr>
<td>轻量级锁</td>
<td>竞争的线程不会阻塞，提高响应速度</td>
<td>如果始终得不到锁竞争的线程，使用自旋消耗CPU</td>
<td>追求响应时间，同步块执行速度快</td>
</tr>
<tr>
<td>重量级锁</td>
<td>线程竞争不适用自旋，不会消耗CPU</td>
<td>阻塞线程，响应时间缓慢</td>
<td>追求吞吐量</td>
</tr>
</tbody>
</table>
<h3 id="彻底搞懂锁升级"><a href="#彻底搞懂锁升级" class="headerlink" title="彻底搞懂锁升级"></a>彻底搞懂锁升级</h3><p>一张图彻底搞懂锁升级。<br><img src="https://s2.ax1x.com/2019/05/26/VElso9.png" alt="在这里插入图片描述"></p>
<h1 id="lock"><a href="#lock" class="headerlink" title="lock"></a>lock</h1><p>它是在1.5之后提供的一个独占锁接口，它的实现类是ReentrantLock，相比较synchronized这种隐式锁（不用手动加锁和释放锁）的便捷性，但是提供了更加锁的可操作性、可中断的获取锁以及超时获取锁等多种synchronized不具备的特性。</p>
<h2 id="使用方法"><a href="#使用方法" class="headerlink" title="使用方法"></a>使用方法</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">Lock lock=new ReentrantLock（）;</span><br><span class="line">lock.lock；</span><br><span class="line">try&#123;</span><br><span class="line">//需要同步的操作&#125;finally&#123;</span><br><span class="line">lock.unlock（）;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>在finally中释放锁，目的保证获取锁最终被释放。不要在获取锁写在try里，因为如果在获取锁时发生了异常，异常抛出的同时，也会导致锁无故释放。</p>
<table>
<thead>
<tr>
<th>方法</th>
<th>描述</th>
</tr>
</thead>
<tbody>
<tr>
<td>void lock（）</td>
<td>获取锁，调用该方法的当前线程将会获取锁</td>
</tr>
<tr>
<td>void lockInterruptibly（） throws InterruptedExcetion</td>
<td>可中断获取锁，与lock不同的是，在锁的获取中可以中断当前线程</td>
</tr>
<tr>
<td>boolean trylock（）</td>
<td>尝试非阻塞获取锁，如果获取成功返回true，否则false</td>
</tr>
<tr>
<td>boolean trylock（long time，TimeUnit unit）</td>
<td>超时获取锁，会有三种情况：1.当前线程在时间内获得了锁返回true，2.在时间内被中断返回false，3.到达超时时间返回false</td>
</tr>
<tr>
<td>void unlock（）</td>
<td>释放锁</td>
</tr>
</tbody>
</table>
<h2 id="AQS"><a href="#AQS" class="headerlink" title="AQS"></a>AQS</h2><p><strong>AQS是队列同步器（AbstractQueuedSynchronizer），是用来构建锁或者其他同步器的基础框架，它使用了一个int成员变量表示同步状态，通过内置的FIFO队列来完成资源获取的线程排队工作问题。AQS在内部维护了一个单一的状态信息state，可以通过getState、setState、compareAndSetState（CAS操作）修改此值。</strong>对于ReentrantLock来说，state可以用来表示当前线程获取锁的可重入次数。ReentrantLock中当一个线程获取了锁，在AQS的内部会进行compareAndSetState将state变为1，如果再次获取就设置为2，释放锁也会去修改state值，只有当值变为0时，其他线程才能获得锁。</p>
<h2 id="锁的介绍"><a href="#锁的介绍" class="headerlink" title="锁的介绍"></a>锁的介绍</h2><p>AQS底层维护state和队列来实现独占和共享两种锁。<br>独占锁：每次只能有一个线程能持有锁，如lock、synchronized。<br>共享锁：允许多个线程同时获取锁，并发访问共享资源，如ReadWriteLock。<br>lock分为公平锁和非公平锁，实现了AQS接口，通过FIFO设置锁的优先级。<br>公平锁：根据线程获取锁的时间来判断，等待时间越久的线程优先被执行。Lock中初始化的时候ReentrantLock（true），默认为false，效率较低因为需要判断线程的等待时间。<br>非公平锁：抢占锁资源，不能保证获取锁的线程优先级，效率较高，因为获取锁是竞争的。</p>
<h2 id="两者不同"><a href="#两者不同" class="headerlink" title="两者不同"></a>两者不同</h2><p> <strong>1. synchronized是Java的关键字，lock是提供的类。</strong><br> <strong>2. synchronized提供不需要手动加锁和释放的隐式锁，释放锁的条件是代码执行完或者抛出异常自动释放。lock必须手动加锁和释放锁，另外还提供了可中断锁、超时获取锁、判断锁状态。</strong><br> <strong>3.  synchronized是可重入、不可中断、非公平，lock是可重入、可中断、公平（两者皆可）。</strong><br> <strong>4. synchronized适合代码量少的同步，lock适合代码量同步多的。</strong></p>
<h2 id="Condition接口"><a href="#Condition接口" class="headerlink" title="Condition接口"></a>Condition接口</h2><p>在Java并发二中有一道生产者消费者，使用的是synchronized+wait（notify），lock中也提供了这种等待通知类型的方法await和signal，当前线程调用这些方法时，需要提前获取到Condition对象关联的锁，Condition是依赖于Lock对象，调用lock对象中的newCondition。<br>老样子还是先定义一个容器：<br><img src="https://s2.ax1x.com/2019/05/26/VEl6iR.png" alt="在这里插入图片描述"><br>生产者：启5个线程往容器里添加数据。<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line">for (int i = 0; i &lt;5 ; i++) &#123;</span><br><span class="line">            new Thread(()-&gt;&#123;</span><br><span class="line">                // 不停生产</span><br><span class="line">                while (true)&#123;</span><br><span class="line">                    // 加锁</span><br><span class="line">                    lock.lock();</span><br><span class="line">                    try &#123;</span><br><span class="line">                        // 判断是否满了 想一想while和if区别</span><br><span class="line">                       while (list.size()==max)&#123;</span><br><span class="line">                           System.out.println(&quot;生产者&quot;+Thread.currentThread().getName()+&quot;:被阻塞&quot;);</span><br><span class="line">                           // 生产者阻塞</span><br><span class="line">                           productor.await();</span><br><span class="line">                       &#125;</span><br><span class="line">                        // 随机产生100以内的数</span><br><span class="line">                        int nextInt = new Random().nextInt(100);</span><br><span class="line">                        list.add(nextInt);</span><br><span class="line">                        System.out.println(&quot;生产者&quot;+Thread.currentThread().getName()+&quot;生产:&quot;+nextInt);</span><br><span class="line">                        // 通知消费者消费</span><br><span class="line">                        consumer.signalAll();</span><br><span class="line">                    &#125; catch (InterruptedException e) &#123;</span><br><span class="line">                        e.printStackTrace();</span><br><span class="line">                    &#125; finally &#123;</span><br><span class="line">                        // 解锁</span><br><span class="line">                          lock.unlock();</span><br><span class="line">                    &#125;</span><br><span class="line">                &#125;</span><br><span class="line"></span><br><span class="line">            &#125;,&quot;productor&quot;).start();</span><br><span class="line">        &#125;</span><br></pre></td></tr></table></figure></p>
<p>消费者：启10线程消费数据</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line">for (int i = 0; i &lt;10 ; i++) &#123;</span><br><span class="line">           new Thread(()-&gt;&#123;</span><br><span class="line">               // 不停消费</span><br><span class="line">               while (true)&#123;</span><br><span class="line">                   // 加锁</span><br><span class="line">                   lock.lock();</span><br><span class="line">                   try &#123;</span><br><span class="line">                       // 判断是否为空</span><br><span class="line">                       while (list.isEmpty())&#123;</span><br><span class="line">                           System.out.println(&quot;消费者&quot;+Thread.currentThread().getName()+&quot;:被阻塞&quot;);</span><br><span class="line">                           // 为空消费者阻塞</span><br><span class="line">                           consumer.await();</span><br><span class="line">                       &#125;</span><br><span class="line">                       // 不为空 消费数据</span><br><span class="line">                       System.out.println(&quot;消费者&quot;+Thread.currentThread().getName()+&quot;消费:&quot;+list.remove());</span><br><span class="line">                       // 唤醒生产者生产数据</span><br><span class="line">                       productor.signalAll();</span><br><span class="line">                   &#125; catch (InterruptedException e) &#123;</span><br><span class="line">                       e.printStackTrace();</span><br><span class="line">                   &#125; finally &#123;</span><br><span class="line">                       // 解锁</span><br><span class="line">                     lock.unlock();</span><br><span class="line">                   &#125;</span><br><span class="line">               &#125;</span><br><span class="line">           &#125;,&quot;consumer&quot;).start();</span><br><span class="line">       &#125;</span><br></pre></td></tr></table></figure>
<p>注释基本明确，就不多说了。wait和notify是配合synchronized使用，await和signal是配合lock使用，区别在于唤醒时notify不能指定线程唤醒，signal可以唤醒具体的线程，更小的粒度控制锁。</p>

      
    </div>
    
    
    
	<div>
      
        
<div class="my_post_copyright">
  <script src="//cdn.bootcss.com/clipboard.js/1.5.10/clipboard.min.js"></script>
  
  <!-- JS库 sweetalert 可修改路径 -->
  <script src="https://cdn.bootcss.com/jquery/2.0.0/jquery.min.js"></script>
  <script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
  <p><span>本文标题:</span><a href="/blog/2019/05/26/Java并发编程四synchronized和lock/">Java并发编程四synchronized和lock</a></p>
  <p><span>文章作者:</span><a href="/" title="访问 zhaoSir 的个人博客">zhaoSir</a></p>
  <p><span>发布时间:</span>2019年05月26日 - 13:18</p>
  <p><span>最后更新:</span>2019年06月03日 - 20:38</p>
  <p><span>原始链接:</span><a href="/blog/2019/05/26/Java并发编程四synchronized和lock/" title="Java并发编程四synchronized和lock">https://zgsir.gitee.io/blog/2019/05/26/Java并发编程四synchronized和lock/</a>
    <span class="copy-path" title="点击复制文章链接"><i class="fa fa-clipboard" data-clipboard-text="https://zgsir.gitee.io/blog/2019/05/26/Java并发编程四synchronized和lock/" aria-label="复制成功！"></i></span>
  </p>
  <p><span>许可协议:</span><i class="fa fa-creative-commons"></i> <a rel="license" href="https://creativecommons.org/licenses/by-nc-nd/4.0/" target="_blank" title="Attribution-NonCommercial-NoDerivatives 4.0 International (CC BY-NC-ND 4.0)">署名-非商业性使用-禁止演绎 4.0 国际</a> 转载请保留原文链接及作者。</p>  
</div>
<script> 
    var clipboard = new Clipboard('.fa-clipboard');
      $(".fa-clipboard").click(function(){
      clipboard.on('success', function(){
        swal({   
          title: "",   
          text: '复制成功',
          icon: "success", 
          showConfirmButton: true
          });
        });
    });  
</script>

      
</div>
   <div>
    
    <div>
    
        <div style="text-align:center;color: #111;font-size:16px;">-------------------------------------本文结束<i class="fa fa-paw"></i>感谢您的阅读-------------------------------------</div>
    
</div>
    
    </div>
   

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/blog/tags/synchronized/" rel="tag"><i class="fa fa-tag"> </i> synchronized</a>
          
            <a href="/blog/tags/lock/" rel="tag"><i class="fa fa-tag"> </i> lock</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/blog/2019/05/25/Java并发编程三volatile使用/" rel="next" title="Java并发编程三volatile使用">
                <i class="fa fa-chevron-left"></i> Java并发编程三volatile使用
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/blog/2019/05/27/Java并发编程五Atomic原子类/" rel="prev" title="Java并发编程五Atomic原子类">
                Java并发编程五Atomic原子类 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
      <div id="lv-container" data-id="city" data-uid="MTAyMC80NDMyMC8yMDg1Mw=="></div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="/blog/images/head.jpeg" alt="zhaoSir">
            
              <p class="site-author-name" itemprop="name">zhaoSir</p>
              <p class="site-description motion-element" itemprop="description">让人迷茫的原因的只有一个，那就是本该拼搏的年纪，想得太多，做得太少。</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/blog/archives/">
              
                  <span class="site-state-item-count">10</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/blog/categories/index.html">
                  <span class="site-state-item-count">2</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/blog/tags/index.html">
                  <span class="site-state-item-count">19</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#synchronized"><span class="nav-number">1.</span> <span class="nav-text">synchronized</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#为什么使用synchronized"><span class="nav-number">1.1.</span> <span class="nav-text">为什么使用synchronized</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#什么是synchronized"><span class="nav-number">1.2.</span> <span class="nav-text">什么是synchronized</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#synchronized机制"><span class="nav-number">1.3.</span> <span class="nav-text">synchronized机制</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#synchronized使用场景"><span class="nav-number">1.4.</span> <span class="nav-text">synchronized使用场景</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#synchronized锁升级"><span class="nav-number">1.5.</span> <span class="nav-text">synchronized锁升级</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#偏向锁"><span class="nav-number">1.5.1.</span> <span class="nav-text">偏向锁</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#CAS"><span class="nav-number">1.5.2.</span> <span class="nav-text">CAS</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#轻量级锁"><span class="nav-number">1.5.3.</span> <span class="nav-text">轻量级锁</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#锁的优缺点"><span class="nav-number">1.5.4.</span> <span class="nav-text">锁的优缺点</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#彻底搞懂锁升级"><span class="nav-number">1.5.5.</span> <span class="nav-text">彻底搞懂锁升级</span></a></li></ol></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#lock"><span class="nav-number">2.</span> <span class="nav-text">lock</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#使用方法"><span class="nav-number">2.1.</span> <span class="nav-text">使用方法</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#AQS"><span class="nav-number">2.2.</span> <span class="nav-text">AQS</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#锁的介绍"><span class="nav-number">2.3.</span> <span class="nav-text">锁的介绍</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#两者不同"><span class="nav-number">2.4.</span> <span class="nav-text">两者不同</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Condition接口"><span class="nav-number">2.5.</span> <span class="nav-text">Condition接口</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
<script type="text/javascript" src="/blog/js/src/love.js"></script>
<div class="copyright">&copy; <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">zhaoSir</span>

  
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>
    
      <span class="post-meta-item-text">博客字总数&#58;</span>
    
    <span title="博客字总数">20.8k</span>
  
  
</div>




        
<div class="busuanzi-count">
  <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  

  
</div>








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  


  











  
  
    <script type="text/javascript" src="/blog/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/canvas-nest/canvas-nest.min.js"></script>
  


  


  <script type="text/javascript" src="/blog/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/blog/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/blog/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/blog/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/blog/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  
    <script type="text/javascript">
      (function(d, s) {
        var j, e = d.getElementsByTagName(s)[0];
        if (typeof LivereTower === 'function') { return; }
        j = d.createElement(s);
        j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
        j.async = true;
        e.parentNode.insertBefore(j, e);
      })(document, 'script');
    </script>
  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/blog/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  

  

  

<script src="/blog/live2dw/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script><script>L2Dwidget.init({"pluginRootPath":"live2dw/","pluginJsPath":"lib/","pluginModelPath":"assets/","model":{"jsonPath":"/blog/live2dw/assets/koharu.model.json"},"display":{"position":"right","width":150,"height":320},"mobile":{"show":true},"log":false,"tagMode":false});</script></body>
</html>
